package com.itzxx.huazhun.utils

import android.content.Context
import android.text.TextUtils
import com.itzxx.huazhun.data.dao.CollectionEntity
import com.itzxx.huazhun.data.dao.DbHelper
import com.itzxx.library_base_ktx.ext.util.loge
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import java.io.File
import java.io.FileOutputStream
import java.lang.Boolean
import java.security.MessageDigest
import kotlin.Int
import kotlin.String


/**
 * Desc:
 *
 * Author: zhangxiaoxiao
 * Date: 2024/8/7 16:43
 * Updater:
 * Update Time:
 * Update Comments:
 */
object  ExcelUtil {

    /**
     * 导出execl
     */
    fun exportExcel(context: Context, collectionRecord: CollectionEntity):String{
        //采集探头具体数值记录，多个关联记录一个
        val probeRecordList =
            DbHelper.init().getProbeRecordDao().getProbeRecordList(collectionRecord.probe_mac, collectionRecord.recordStartTime)

        // 创建excel xlsx格式
        val wb: Workbook = HSSFWorkbook()

        // 创建工作表
        val sheet: Sheet = wb.createSheet()

        //创建行对象
        var row: Row = sheet.createRow(0)

        // 设置有效数据的行数和列数，默认3个
        //1、序号；2、日期/时间 3、探头数据（可能有两路，默认一路）
        val colNum: Int = 2
        //先处理前面两个固定的
        for (index in 0 until colNum) {
            // 显示20个字符的宽度  列宽
            sheet.setColumnWidth(index, 30 * 256)
            val cell1 = row.createCell(index)

            when (index) {
                0 -> {
                    //第一行
                    cell1.setCellValue("序号")
                }

                1 -> {
                    cell1.setCellValue("日期/时间")
                }
            }
        }
        for (index in 0 until collectionRecord.wayNum) {
            // 显示20个字符的宽度  列宽
            sheet.setColumnWidth(colNum + index, 30 * 256)
            val cell1 = row.createCell(colNum + index)
            //1个格式：[1] 2个格式：[1,2]
            var channel = collectionRecord.wayIndex.replace("[", "").replace("]", "")
            when (index) {
                0 -> {
                    //有两个
                    if (collectionRecord.wayNum > 1) {
                        channel = channel.split(",")[0]
                    }
                    //第一个渠道
                    cell1.setCellValue("#${collectionRecord.recordId}-${collectionRecord.probe_mac.replace(":","")}-${channel}".replace(" ",""))
                }

                1 -> {
                    val channelList = channel.split(",")
                    //第一个渠道
                    cell1.setCellValue("#${collectionRecord.recordId}-${collectionRecord.probe_mac.replace(":","")}-${channelList[1]}".replace(" ",""))
                }
            }
        }
        //总共多少列
        val totalRow = colNum + collectionRecord.wayNum
        //开始拼接数据
        probeRecordList.forEachIndexed { index, probeRecordEntity ->
            if (collectionRecord.recordNum > index) {
                // 之所以rowNum + 1 是因为要设置第二行单元格
                row = sheet.createRow(index + 1);
                // 设置单元格显示宽度
                row.heightInPoints = 28f;
                for (i in 0 until totalRow) {
                    val cell = row.createCell(i)
                    when (i) {
                        0 -> {
                            //序号
                            cell.setCellValue((index + 1).toString())
                        }

                        1 -> {
                            cell.setCellValue(
                                DateUtil.getYMDHMSStr((probeRecordEntity.recordStartTime + "000").toLong() + index * probeRecordEntity.recordSamplingInterval.toLong() * 1000)
                            )
                        }

                        2 -> {
                            if (collectionRecord.wayNum > 1) {
                                cell.setCellValue(probeRecordEntity.airPressure.toString())
                            } else {
                                val channel =
                                    collectionRecord.wayIndex.replace("[", "").replace("]", "")
                                if (TextUtils.equals(channel, "0")) {
                                    cell.setCellValue(probeRecordEntity.airPressure.toString())
                                } else {
                                    cell.setCellValue(probeRecordEntity.temperature.toString())
                                }
                            }
                        }

                        3 -> {
                            cell.setCellValue(probeRecordEntity.temperature.toString())
                        }
                    }
                }
            }
        }
        val filePath = "${context.getExternalFilesDir("")}/${md5(collectionRecord.probe_mac + collectionRecord.recordStartTime)}.xlsx"
        val excel = File(filePath)
        if (excel.exists()){
            excel.delete()
        }
        excel.createNewFile()
//        if (!excel.exists()) {
//            excel.createNewFile()
//        }else{
//            val newFileName = getXlsxNewFileName(excel)
//            excel = File(newFileName)
//            excel.createNewFile()
//        }
        " 导出路径${excel.getPath()}".loge()
        val fos = FileOutputStream(excel)
        wb.write(fos)
        wb.close()
        fos.flush()
        fos.close()
        return  excel.getPath()
    }


    /** md5加密 */
    private fun md5(content: String): String {
        val hash = MessageDigest.getInstance("MD5").digest(content.toByteArray())
        val hex = StringBuilder(hash.size * 2)
        for (b in hash) {
            var str = Integer.toHexString(b.toInt())
            if (b < 0x10) {
                str = "0$str"
            }
            hex.append(str.substring(str.length - 2))
        }
        return hex.toString()
    }

    private fun getXlsxNewFileName(file: File): String {
        if (file.exists()) {
            val newPath = file.path.substring(0, file.path.length - 5) + "(1).xlsx"
            return getXlsxNewFileName(File(newPath))
        } else {
            return file.path
        }
    }
}